package org.df.ulab.util.gui.config;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.configuration.Configuration;
import org.df.ulab.util.gui.actions.NextAction;
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

/**
 * @author Daniel Filgueiras
 * @since 19/06/2011
 */
public class Frame {

	private static final DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy");
	
	private String description;
	private Configuration config;
	
	private Frame nextFrame;
	private List<FrameField> fields = new ArrayList<FrameField>();
	
	private NextAction action;
	
	public Frame(String description, Configuration config) {
		super();
		this.description = description;
		this.config = config;
	}
	
	public Frame createField(String configKey, Class<?> valueClass, String description) {
		FrameField field = new FrameField(configKey, valueClass, description);
		
		fields.add(field);
		
		return this;
	}
	
	public Frame createField(String configKey, String description) {
		return createField(configKey, String.class, description);
	}
	
	public Frame createNextFrame(String description) {
		nextFrame = new Frame(description, config);
		return nextFrame;
	}

	public Frame setAction(NextAction action) {
		this.action = action;
		return this;
	}
	
	public void setNextFrame(Frame nextFrame) {
		this.nextFrame = nextFrame;
	}
	public Frame getNextFrame() {
		return nextFrame;
	}
	
	public String getDescription() {
		return description;
	}
	public Configuration getConfig() {
		return config;
	}
	public List<FrameField> getFields() {
		return fields;
	}
	public NextAction getAction() {
		return action;
	}

	public String getFieldValue(FrameField field) {
		
		Object obj = this.config.getProperty(field.getConfigKey());
		if (obj == null)
			return "";
		
		if (obj.getClass().equals(LocalDate.class)) {
			return formatter.print((LocalDate)obj);
		} 
		return this.config.getProperty(field.getConfigKey()).toString();
	}
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public void setFieldValue(FrameField field, String value) {
		
		if (value == null)
			return;
		
		if (field.getValueClass().equals(String.class)) {
			this.config.setProperty(field.getConfigKey(), value);
		} else if (field.getValueClass().equals(LocalDate.class)) {
			this.config.setProperty(field.getConfigKey(), formatter.parseDateTime(value).toLocalDate());
		} else if (field.getValueClass().isEnum()) {
			Class<? extends Enum> eClass = field.getValueClass().asSubclass(Enum.class);
			Enum<?> eValue = Enum.valueOf(eClass, value);
			this.config.setProperty(field.getConfigKey(), eValue);
		}
		
	}
}
